package one.stand.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jmp.api.dto.CustomerRecordRequest;
import com.jmp.api.dto.CustomerRecordResponse;
import com.jmp.api.dto.SeeRecordCustomerAnalysisRequests;
import com.jmp.api.dto.SeeRecordCustomerAnalysisResponse;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageRequest;
import one.stand.dto.PageResponse2;
import one.stand.dto.UserDto;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.*;
import one.stand.model.*;
import one.stand.request.SeeRecordRequest;
import one.stand.response.CrmCustomerAnalysisRespnse;
import one.stand.response.CrmSeeRecordResponse;
import one.stand.response.CustomerAnalysisResponse;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.GoodsBaseService;
import one.stand.service.RecordPublicService;
import one.stand.service.user.UserAdminService;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Api(description = "查看记录系列")
@RestController
@RequestMapping("crmApi/seeRecord")
@Slf4j
public class SeeRecordController extends BaseController {
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private GoodsForwardRecordMapper goodsForwardRecordMapper;
    @Autowired
    private DynamicForwardRecordMapper dynamicForwardRecordMapper;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;

    @Autowired
    private SeeRecordApiCrmMapper seeRecordApiCrmMapper;

    @ApiOperation("圆饼图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "客户ID（用户客户分析）", paramType = "Integer"),
            @ApiImplicitParam(name = "dayNum", value = "天数", paramType = "Integer"),
            @ApiImplicitParam(name = "type", value = "1个人数据2企业数据", paramType = "Integer"),
    })
    @PostMapping("countCustomerAnalysis")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<CrmCustomerAnalysisRespnse>> countCustomerAnalysis(@RequestAttribute SeeRecordRequest request) {

        return crmFegin.countCustomerAnalysis(request);
    }

    @ApiOperation("客户与我的互动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "客户ID（用于客户分析）", paramType = "Integer"),
            @ApiImplicitParam(name = "type", value = "1个人数据2企业数据", paramType = "Integer"),
    })
    @PostMapping("customerAnalysis")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<SeeRecordCustomerAnalysisResponse> customerAnalysis(@RequestAttribute SeeRecordCustomerAnalysisRequests request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getType() == null) {
            request.setType(2);
        }
        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        Integer userId = Objects.nonNull(request.getUserId()) ? request.getUserId() : null;
        Integer cardId = request.getType() == 1 ? optUser.getCardId() : request.getCardId();
        Integer companyId = optUser.getCompanyId();

        // 客户与自己的沟通次数
        Long imNum = recordPublicService.consultCount(userId, cardId, companyId);
        // 获取客户拨打我的电话次数
        Long callsNum = recordPublicService.callCount(userId, cardId, companyId);
        //商品转发次数
        Long goodForwardNum = goodsForwardRecordMapper.count(new GoodsForwardRecordModel() {{
            setUserId(userId);
            setCompanyCardId(cardId);
            setCompanyId(companyId);
        }});
        //评论次数
        Long commentNum = recordPublicService.countComment(userId, companyId);
        //文章转发次数
        Long dynamicNum = dynamicForwardRecordMapper.count(new DynamicForwardRecordModel() {{
            setUserId(userId);
            setCompanyCardId(cardId);
            setCompanyId(companyId);
        }});
        //客户信息
        CustomerAnalysisResponse analysisModel = new CustomerAnalysisResponse();
        if (Objects.nonNull(userId)) {
            // 员工卡片，客户id，查看类型（2产品）
            analysisModel = seeRecordPublicMapper.getCustomerAnalysis(optUser.getCardId(), userId, SeeRecordEnums.PRODUCT.getCode(), companyId);
            analysisModel.setName(StringUtils.isBlank(analysisModel.getName()) ? "" : new String(Base64.getDecoder().decode(analysisModel.getName().getBytes())));
        }
        SeeRecordCustomerAnalysisResponse response = SeeRecordCustomerAnalysisResponse.builder()
                .imNum(imNum)
                .callsNum(callsNum)
                .goodForwardNum(goodForwardNum)
                .commentNum(commentNum)
                .dynamicNum(dynamicNum)
                .analysisModel(analysisModel)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("名片查看记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "客户id（查询客户的各种记录）", paramType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "entranceType", value = "入口类型（1:时间追踪，2：行为追踪，3：ai分析,4,成交率（查看类型必须是2））", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "seeType", value = "查看类型 1:名片，2:产品，3：官网,4:查看动态", paramType = "Integer"),
    })
    @PostMapping("getSeeRecordList")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<CrmSeeRecordResponse>> getSeeRecordList(@RequestAttribute SeeRecordRequest request) {
        log.info("ai分析：{}", JSON.toJSONString(request));
        if (request.getEntranceType() == null) {
            return ResultModel.checkParamFail();
        }
        //ai分析验证 和行为追踪都需要查看类型
        if (request.getEntranceType() == 3 || request.getEntranceType() == 2) {
            if (request.getSeeType() == null) {
                return ResultModel.checkParamFail();
            }
        }
        //时间追踪不需要查看类型
        if (request.getEntranceType() == 1 || request.getEntranceType() == 4) {
            request.setSeeType(null);
        }

        // select
        Integer cardId = Objects.nonNull(request.getCardId()) ? request.getCardId() : request.getMyCardId();// 企业管理-员工详情中 查询员工数据而不是当前登录人
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels;

        if (request.getEntranceType() == 1
                && Objects.isNull(request.getSeeType())
                && Objects.isNull(request.getCardId())
                && Objects.isNull(request.getUserId())) {//首页雷达
            crmSeeRecordModels = seeRecordApiCrmMapper.selectUser(cardId);
        } else if (request.getEntranceType() == 1) {
            crmSeeRecordModels = seeRecordApiCrmMapper.select(request.getUserId(),
                    request.getSeeType(),
                    cardId);
        } else {
            crmSeeRecordModels = seeRecordApiCrmMapper.getCrmSeeRecord2(request.getUserId(),
                    request.getEntranceType(),
                    request.getSeeType(),
                    cardId);
        }

        PageInfo<CrmSeeRecordModel> pageInfo = new PageInfo(crmSeeRecordModels);
        List<CrmSeeRecordResponse> crmSeeRecordResponseList = new ArrayList<>();
        if (request.getEntranceType() != 1) {
            pageInfo.getList().forEach(c -> {
                CrmSeeRecordResponse recordResponse = new CrmSeeRecordResponse();
                BeanUtils.copyProperties(c, recordResponse);
                recordResponse.setNickName(StringUtils.isBlank(c.getNickName()) ? "" : new String(java.util.Base64.getDecoder().decode(c.getNickName())));
                //这里都使用微信昵称
                recordResponse.setName(recordResponse.getNickName());
                // formNum
                recordResponse.setFormNum(recordPublicService.formIdCount(c.getUserId().intValue(), RecordPublicService.FORM_ID_TYPE_USER));
                crmSeeRecordResponseList.add(recordResponse);
            });
        } else {
            pageInfo.getList().forEach(c -> {
                CrmSeeRecordResponse recordResponse = new CrmSeeRecordResponse();
                BeanUtils.copyProperties(c, recordResponse);

                // formNum
                recordResponse.setFormNum(recordPublicService.formIdCount(c.getUserId().intValue(), RecordPublicService.FORM_ID_TYPE_USER));

                recordResponse.setNum(c.getRanking());

                if (recordResponse.getSeeType() == 2) {
                    Goods goods = goodsBaseService.get(c.getItmeId());
                    if (Objects.nonNull(goods)) {
                        recordResponse.setTargetName(goods.getGoodsName());
                    }
                } else if (recordResponse.getSeeType() == 5) {
                    Article article = articleMapper.selectByPrimaryKey(c.getItmeId());
                    if (Objects.nonNull(article)) {
                        recordResponse.setTargetName(article.getTitle());
                    }
                }

                if (Objects.nonNull(c.getCardId())) {
                    BusinessCard businessCard = businessCardBaseService.getCustomer(c.getCardId());
                    if (Objects.nonNull(businessCard)) {
                        recordResponse.setPersonalWx(businessCard.getPersonalWx());
                    }
                }
                if (Objects.nonNull(c.getUserId())) {
                    UserDto user = userAdminService.get(c.getUserId().intValue());
                    recordResponse.setNickName(user.getName());
                    recordResponse.setName(user.getName());//这里都使用微信昵称
                    recordResponse.setLogo(user.getUserImg());
                    recordResponse.setPhone(user.getPhone());
                }
                crmSeeRecordResponseList.add(recordResponse);
            });
        }
        return ResultModel.success(crmSeeRecordResponseList);
    }


    @ApiOperation("雷达-时间追踪")
    @PostMapping("ai/time")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<CrmSeeRecordResponse>> aiTime(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordApiCrmMapper.selectUserAll(optUser.getCardId());

        List<CrmSeeRecordResponse> crmSeeRecordResponseList = ConvertUtils.list(crmSeeRecordModels, c -> {
            CrmSeeRecordResponse recordResponse = new CrmSeeRecordResponse();
            BeanUtils.copyProperties(c, recordResponse);

            // formNum
            recordResponse.setFormNum(recordPublicService.formIdCount(c.getUserId().intValue(), RecordPublicService.FORM_ID_TYPE_USER));

            recordResponse.setNum(c.getRanking());

            if (recordResponse.getSeeType() == 2) {
                Goods goods = goodsBaseService.get(c.getItmeId());
                if (Objects.nonNull(goods)) {
                    recordResponse.setTargetName(goods.getGoodsName());
                }
            } else if (recordResponse.getSeeType() == 5) {
                Article article = articleMapper.selectByPrimaryKey(c.getItmeId());
                if (Objects.nonNull(article)) {
                    recordResponse.setTargetName(article.getTitle());
                }
            }

            if (Objects.nonNull(c.getCardId())) {
                BusinessCard businessCard = businessCardBaseService.getCustomer(c.getCardId());
                if (Objects.nonNull(businessCard)) {
                    recordResponse.setPersonalWx(businessCard.getPersonalWx());
                }
            }
            if (Objects.nonNull(c.getUserId())) {
                UserDto user = userAdminService.get(c.getUserId().intValue());
                recordResponse.setNickName(user.getName());
                recordResponse.setName(user.getName());//这里都使用微信昵称
                recordResponse.setLogo(user.getUserImg());
                recordResponse.setPhone(user.getPhone());
            }

            String typeName = SeeRecordEnums.getByCode(c.getSeeType()).getMessage();
            if (StringUtils.isNoneBlank(recordResponse.getTargetName())) {
                typeName = typeName + ": " + recordResponse.getTargetName();
            }
            recordResponse.setContent("正在<span class=\"cblue\">查看</span>你的" + typeName + "，累计与你互动<span class=\"cblue\">" + c.getRanking() + "</span>次");

            return recordResponse;
        });
        return ResultModel.success(crmSeeRecordResponseList);
    }

    @ApiOperation("客户分析-互动记录")
    @PostMapping("customer/record")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<PageResponse2<CustomerRecordResponse.Record>> customerRecord(@RequestAttribute CustomerRecordRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CrmSeeRecordModel> crmSeeRecordModels = seeRecordApiCrmMapper.getCrmSeeRecord(request.getUserId(), request.getMyCardId());

//        User user = userAdminService.getByUserId(request.getUserId());
//        String nickName = Objects.nonNull(user) ? userAdminService.getNickNameDecode(user.getNickeName()) : StringUtils.EMPTY;

        PageResponse2<CustomerRecordResponse.Record> response = ConvertUtils.page2(crmSeeRecordModels, crmSeeRecordModel -> {
            String content;
            if (crmSeeRecordModel.getSeeType() == 1) {
                content = "Ta正在查看名片第" + crmSeeRecordModel.getRanking() + "次，现在沟通，效率更高哦";
            } else if (crmSeeRecordModel.getSeeType() == 3) {
                content = "Ta正在查看官网第" + crmSeeRecordModel.getRanking() + "次，有望合作";
            } else if (crmSeeRecordModel.getSeeType() == 4) {
                content = "Ta正在查看动态第" + crmSeeRecordModel.getRanking() + "次，合作意向很强烈";
            } else if (crmSeeRecordModel.getSeeType() == 2) {
                String targetName;
                if (Objects.isNull(crmSeeRecordModel.getItmeId())) {
                    targetName = "产品列表";
                } else {
                    Goods goods = goodsBaseService.get(crmSeeRecordModel.getItmeId());
                    if (Objects.nonNull(goods)) {
                        targetName = goods.getGoodsName() + "产品";
                    } else {
                        targetName = "产品";
                    }
                }
                content = "Ta正在查看" + targetName + "，累计查看产品" + crmSeeRecordModel.getRanking() + "次，尽快把握商机。";
            } else if (crmSeeRecordModel.getSeeType() == 5) {
                content = "Ta正在查看头条文章第" + crmSeeRecordModel.getRanking() + "次";
            } else {
                content = StringUtils.EMPTY;
            }
            return CustomerRecordResponse.Record.builder()
                    .targetName(content)
                    .createTime(crmSeeRecordModel.getCreateTime())
                    .build();
        });
        return ResultModel.success(response);
    }

}
